package mblog.web.job;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.ansj.app.keyword.KeyWordComputer;
import org.ansj.app.keyword.Keyword;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;

import mblog.web.qiniu.UploadImg;

public class ProcessUtil {
	private static Map<String, String> cookies = new HashMap<>();
	private static String userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36";
	private static String NOW_PAGE_URL_FILE = "XiNiuGuShiPageURL.txt";// 当前页url";
	private static String LUOSH_SPIDER_LOG = "D:/luoshSpiderLog/"; // "D:/tysSpiderLog/";
	private static String NEW_PIC_DIR = "D:/luoshSpiderLog/jianshu_pic/";
	private static String QINIU_DOMAIN = "http://luosh.qiniudn.com/";

	/**
	 * 获取当前页URL
	 * 
	 * @param tid
	 * @return
	 */
	public static String getNowPageUrl() {
		String NOW_PAGE_URL = "";
		try {
			File f = new File(LUOSH_SPIDER_LOG + NOW_PAGE_URL_FILE);
			NOW_PAGE_URL = FileUtils.readFileToString(f);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return NOW_PAGE_URL;
	}

	/**
	 * 发送到mblog
	 * 
	 * @param artcleMap
	 * @throws IOException
	 */
	public static void postRsltMap(Map<String, String> artcleMap) {
		if (null == (artcleMap.get("content"))) {
			artcleMap.get("errorUrl");
			return;
		}

		MblogPost.post(artcleMap);
	}

	public static void saveHtmFile(String text) throws IOException {
		String fileName = /* UUID.randomUUID() + */ "12.html";
		FileWriter fw = new FileWriter(new File(NEW_PIC_DIR + fileName));
		fw.write(text);
		fw.close();
	}

	// 获取图片并上传到七牛云
	public static String getNewImgUrl(String imgUrlStr) throws IOException {
		String luoshPicPath = "";
		System.out.println("保存图片：" + imgUrlStr);
		String fileName = UUID.randomUUID() + ".png";// 暂时写死PNG
		// jpg, jpeg, gif, png
		if (imgUrlStr.endsWith(".jpg")) {
			fileName = fileName.substring(0, fileName.length() - 4) + ".jpg";
		} else if (imgUrlStr.endsWith(".jpeg")) {
			fileName = fileName.substring(0, fileName.length() - 4) + ".jpeg";
		} else if (imgUrlStr.endsWith(".gif")) {
			fileName = fileName.substring(0, fileName.length() - 4) + ".gif";
		}

		/*
		 * URL imgUrl = new URL(imgUrlStr); URLConnection uc =
		 * imgUrl.openConnection(); InputStream is = uc.getInputStream();
		 * OutputStream os = new FileOutputStream(new File(NEW_PIC_DIR +
		 * fileName)); IOUtils.copy(is, os);
		 */
		try {
			new UploadImg().upload(imgUrlStr, fileName);
			luoshPicPath = QINIU_DOMAIN + fileName;
		} catch (Exception e) {
			luoshPicPath = "http://luosh.qiniudn.com/1083963-d4743637b8fbdb6a.jpg";
		}
		return luoshPicPath;
	}

	/**
	 * 检查该文章是否已读取
	 * 
	 * @param tid
	 * @return
	 */
	public static Boolean isNewArticle(String tid, String fileName) {
		try {
			File f = new File(LUOSH_SPIDER_LOG + fileName);
			if (FileUtils.readFileToString(f).contains(tid)) {
			} else {
				FileUtils.writeStringToFile(f, tid + ";", true);
				return true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 记录需要手动的文章URL
	 * 
	 * @param url
	 * @return
	 */
	public static Boolean manmalArticle(String url) {
		String fileName = "xiniugushi_err.txt";

		try {
			File f = new File(LUOSH_SPIDER_LOG + fileName);
			FileUtils.forceMkdir(f);
			FileUtils.writeStringToFile(f, url + "\n", true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 获取标签
	 * 
	 * @param title
	 * @param article
	 * @return
	 */
	public static String getTag(String title, String article) {
		KeyWordComputer kwc = new KeyWordComputer(5);
		Collection<Keyword> result = kwc.computeArticleTfidf(title, article);
		String str = result.toString().replaceAll("\\d+", "").replaceAll("/.", "");
		String[] tagArr = str.substring(1, str.length() - 1).split(", ");
		String tmpTag = "";
		for (String t : tagArr) {
			tmpTag += t + ",";
		}
		tmpTag = tmpTag.substring(0, tmpTag.length() - 1);
		System.out.println("标签：" + tmpTag);
		return tmpTag;
	}

	/**
	 * 获取DOCUMENT对象
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public static Document getDoc(String url) throws IOException {
		Response resp = Jsoup.connect(url).userAgent(userAgent).cookies(cookies).execute();
		cookies = resp.cookies();
		// System.out.println("访问："+url);
		System.out.println("返回：" + cookies);
		Document doc = resp.parse();
		return doc;
	}
}
